<?php

namespace WebSocket\Application;

/**
 * Simple Chat Application
 * 
 * @author Mojmir Nebel
 */
class ChatApplication extends Application
{
    private $clients = array();
    private $namedClients = array();
    private $SEPARATOR = "||";
    private $NUMBER_OF_COMMANDS = 4;
    
    /*
     * msg format: command||from||to||message
     */

    public function onConnect($client)
    {
        $this->clients[] = $client;
    }

    public function onDisconnect($client)
    {
        $key = array_search($client, $this->clients);
        if ($key) {
            unset($this->clients[$key]);
        }
        $key = array_search($client, $this->namedClients);
        if ($key) {
            unset($this->clients[$key]);
        }
    }
    
    public function onData($data, $client)
    {
    	$msg = explode($this->SEPARATOR, $data, $this->NUMBER_OF_COMMANDS);
    	$command = $msg[0];
    	$from = $msg[1];
    	$to = $msg[2];
    	$message = $msg[3];
    	switch ($msg[0]) {
    		case "setname":
    			$this->setNameOfClient($client, $message);
    			$client->send("Welcome ".$message."!");
    			break;
    		case "msg":
    			$this->sendMessage($from, $to, $message);
    			break;
    	}
/*        foreach ($this->clients as $sendto) {
        	if ($sendo != $client) {
        		$sendto->send($data);
        	}
        }*/
    }
    
    private function setNameOfClient($client, $name) {
    	$this->namedClients[$name] = $client;
    }
    
    private function sendMessage($from, $to, $message) {
    	foreach ($this->namedClients as $name => $client) {
    		if ($to == "" || $to == $name) {
    		    $client->send($from.": ".$message);
    		}
    	}
    }
}